import pyppeteer
import asyncio
import sys
import requests
from pyppeteer.network_manager import Response, Request
from tqdm import tqdm


class baomi():

    def __init__(self, url):
        self.url = url
        self.page_agent = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36 Edg/125.0.0.0"
        self.headers = {'User-Agent': self.page_agent}

    async def run(self, user_name, user_psw):
        if sys.platform == 'win32':
            userDataDir = rf"d:\pyppeteer_tmp\{user_name}_tmp"
            executablePath = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
            # executablePath = r"C:\Program Files (x86)\Microsoft\Edge Beta\Application\msedge.exe"
        else:
            userDataDir = '/home/duliang/Downloads/xx_tmp'
            executablePath = '/usr/bin/google-chrome'
        browser = await pyppeteer.launch({
            'headless':
            False,
            'args': [
                '--window-size=1920,1080', '--start-maximized', '--no-sandbox',
                '--disable-infobars'
            ],
            'ignoreDefaultArgs': ['--enable-automation'],
            'dumpio':
            True,
            'userDataDir':
            userDataDir,
            'executablePath':
            executablePath
        })
        page = await browser.newPage()
        page.on(
            'response', lambda response: asyncio.ensure_future(
                self.response_handler(response)))
        # 设置用户代理
        await page.setUserAgent(self.page_agent)
        await page.setViewport({'width': 1024, 'height': 800})
        await page.goto(self.url, waitUntil='networkidle2')
        user_name_input = await page.querySelector(
            '#nav > div > div.pageBox > div.container1_box > div > div > div > form > div.el-form-item.input_item.input_item_phone > div > div > input'
        )
        await user_name_input.type(str(user_name))
        user_psw_input = await page.querySelector(
            '#nav > div > div.pageBox > div.container1_box > div > div > div > form > div.el-form-item.input_item.password-item > div > div > input'
        )
        await user_psw_input.type(str(user_psw))
        # slider = await page.waitForSelector(
        #     '#nav > div > div.pageBox > div.container1_box > div > div > div > form > div.sliderBox'
        #     # '#nav > div > div.pageBox > div.container1_box > div > div > div > form > div.sliderBox'
        # )
        slider = await page.waitForSelector(
            '#nav > div > div.pageBox > div.container1_box > div > div > div > form > div.sliderBox'
        )
        # 获取滑块的客户端矩形
        slider_rect = await page.evaluate(
            '''(element) => {
                    //获取滑块的边界矩形
                    const {x,y,left, top, width, height} = element.getBoundingClientRect();
                    //返回边界矩形的属性
                    return {x,y,left, top, width, height};
                }''', slider)
        print(slider_rect)
        # print(
        #     f"Element Rect: Left={rect['left']}, Top={rect['top']}, Width={rect['width']}, Height={rect['height']}"
        # )
        tracker = await page.waitForSelector(
            '#nav > div > div.pageBox > div.container1_box > div > div > div > form > div.sliderBox > div'
        )
        tracker_rect = await page.evaluate(
            '''(element) => {
            const {x,y,left, top, width, height} = element.getBoundingClientRect();
            return {x,y,left, top, width, height};
        }''', tracker)
        print(tracker_rect)
        # 计算拖动距离，这里以拖动到最右侧为例，实际情况可能需要根据需求调整
        drag_to_x = tracker_rect['x'] + tracker_rect['width'] - slider_rect[
            'width']
        drag_to_y = slider_rect['y'] + slider_rect['height'] / 2  # 保持Y轴位置不变
        await page.mouse.move(slider_rect['x'] + slider_rect['width'] / 2,
                              slider_rect['y'] + slider_rect['height'] / 2)
        await page.mouse.down()
        # await page.mouse.click(slider_rect['x'] + slider_rect['width'] / 2,
        #                        slider_rect['y'] + slider_rect['height'] / 2)
        await page.mouse.move(drag_to_x, drag_to_y)
        await page.mouse.up()

        await browser.close()

    async def response_handler(self, response: Response):
        resourceType = response.request.resourceType
        if resourceType in ['xhr']:
            print(response.url)

    def start(self, user_name, user_psw):
        asyncio.get_event_loop().run_until_complete(
            self.run(user_name, user_psw))


if __name__ == '__main__':
    bm = baomi('https://www.baomi.org.cn/login?siteId=95')
    bm.start(13625252252, '821101cCW')
